package com.imooc.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imooc.mall.common.ResultInfo;
import com.imooc.mall.common.ResultInfoUtil;
import com.imooc.mall.dao.ShippingMapper;
import com.imooc.mall.dto.ShippingDto;
import com.imooc.mall.exception.MallException;
import com.imooc.mall.pojo.Shipping;
import com.imooc.mall.service.IShippingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@SuppressWarnings("all")
public class ShippingServiceImpl implements IShippingService {

    @Autowired
    private ShippingMapper shippingMapper;

    @Override
    public ResultInfo<Integer> add(Integer uid, ShippingDto shippingDto) {
        Shipping shipping = new Shipping();
        BeanUtils.copyProperties(shippingDto, shipping);
        shipping.setUserId(uid);
        shipping.setCreateTime(new Date());
        shipping.setUpdateTime(new Date());
        int i = shippingMapper.insertSelective(shipping);
        if (i < 1) {
            throw new MallException("新增地址异常");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("shippingId", shipping.getId());

        return ResultInfoUtil.success(map);
    }

    @Override
    public ResultInfo delete(Integer uid, Integer shippingId) {
        Map map = new HashMap();
        map.put("id", shippingId);
        map.put("uid", uid);
        int i = shippingMapper.deleteByIdAndUid(map);
        if (i < 1) {
            throw new MallException("删除地址异常");
        }
        return ResultInfoUtil.success("删除成功");
    }

    @Override
    public ResultInfo update(Integer uid, Integer shippingId, ShippingDto shippingDto) {
        Shipping shipping = new Shipping();
        BeanUtils.copyProperties(shippingDto, shipping);
        shipping.setUserId(uid);
        shipping.setId(shippingId);
        shipping.setUpdateTime(new Date());
        int i = shippingMapper.updateByPrimaryKeySelective(shipping);
        if (i < 1) {
            throw new MallException("更新失败");
        }
        return ResultInfoUtil.success("更新成功");
    }

    @Override
    public ResultInfo<PageInfo<Shipping>> list(Integer uid, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Shipping> list = shippingMapper.selectByUserId(uid);
        PageInfo pageInfo=new PageInfo(list);
        pageInfo.setList(list);
        return ResultInfoUtil.success(pageInfo);
    }
}
